#include "common.h"
#include "spawn_process.h"

static void on_alloc(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
    buf->base = (char *)malloc(suggested_size);
    buf->len = suggested_size;
}

void process_init(uv_loop_t *loop, process_t *process, char * cmdpath, char *cmdline[])
{
    int ret = -1;

    ret = uv_pipe_init(loop, &process->in, 0);
    ASSERT_UV_OK(ret);

    ret = uv_pipe_init(loop, &process->out, 0);
    ASSERT_UV_OK(ret);

    ret = uv_pipe_init(loop, &process->err, 0);
    ASSERT_UV_OK(ret);

    process->stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE;
    process->stdio[0].data.stream = (uv_stream_t *)&process->in;
    process->stdio[1].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
    process->stdio[1].data.stream = (uv_stream_t *)&process->out;
    process->stdio[2].flags = UV_CREATE_PIPE | UV_WRITABLE_PIPE;
    process->stdio[2].data.stream = (uv_stream_t *)&process->err;

    process->opt.stdio = process->stdio;
    process->opt.stdio_count = 3;
    process->opt.file = (cmdpath != NULL) ? cmdpath : cmdline[0];
    process->opt.args = cmdline;
    process->opt.exit_cb = process->on_exit_cb;

    process->ctx.data = process;

    ret = uv_spawn(loop, &process->ctx, &process->opt);
    ASSERT_UV_OK(ret);

    ret = uv_read_start((uv_stream_t *)&process->out, on_alloc, process->on_read_stdout_cb);
    ASSERT_UV_OK(ret);

    ret = uv_read_start((uv_stream_t *)&process->err, on_alloc, process->on_read_stderr_cb);
    ASSERT_UV_OK(ret);
}

int process_deinit()
{
    return 0;
}

int process_write()
{
}
